import React, { useState } from 'react';
import { Box, TextField, Button, Typography, Paper, Divider } from '@mui/material';
import { useAppContext } from '../contexts/AppContext';
import { parseAbi } from '../utils/abiParser';

const AbiInput: React.FC = () => {
    const { state, dispatch } = useAppContext();
    const [localAbi, setLocalAbi] = useState(state.abi);
    const [localAddress, setLocalAddress] = useState(state.contractAddress);
    const [error, setError] = useState('');

    const handleParse = () => {
        try {
            const methods = parseAbi(localAbi);
            dispatch({ type: 'SET_ABI', payload: localAbi });
            dispatch({ type: 'SET_METHODS', payload: methods });
            dispatch({ type: 'SET_CONTRACT_ADDRESS', payload: localAddress });
            setError('');
        } catch (err) {
            setError(err instanceof Error ? err.message : String(err));
        }
    };

    return (
        <Paper elevation={3} sx={{ p: 3, mb: 3 }}>
            <Typography variant="h6" gutterBottom>
                Contract ABI & Address
            </Typography>
            <Divider sx={{ mb: 2 }} />

            <TextField
                label="Contract Address"
                variant="outlined"
                fullWidth
                value={localAddress}
                onChange={(e) => setLocalAddress(e.target.value)}
                placeholder="0x..."
                sx={{ mb: 2 }}
            />

            <TextField
                label="ABI JSON"
                variant="outlined"
                fullWidth
                multiline
                rows={8}
                value={localAbi}
                onChange={(e) => setLocalAbi(e.target.value)}
                placeholder='[{"constant":true,"inputs":[...]...}]'
                sx={{ mb: 2 }}
            />

            {error && (
                <Typography color="error" sx={{ mb: 2 }}>
                    {error}
                </Typography>
            )}

            <Button
                variant="contained"
                color="primary"
                onClick={handleParse}
                disabled={!localAbi || !localAddress}
            >
                Parse ABI
            </Button>
        </Paper>
    );
};

export default AbiInput;